import React, { useEffect } from 'react';
import { Button, DatePicker, Space } from 'antd';
import moment from 'moment';

import { TjSegmented, TjSelect, TjStation, useTRState } from '@/pages/ETrade/components';
import { querySequence } from './services';
import { tradeOptions } from './helper';
import _ from 'lodash';

const defaultForm = (_data = []) => {
  // 默认表单
  return {
    dates: [moment().startOf('month'), moment().endOf('month')],
    tradeItem: tradeOptions()[0], // [集中竞价,滚动撮合] 选项内有算法参数和交易类型id
    sequenceIdList: [], // 交易序列
    searched: false, // 首次、重置时执行查询的标识
    market: _data[0],
    stations: _data[0].children,
    groupIds: _data?.[0]?.children.map((i) => i.value),
    stationList: getStationList(_data?.[0]?.children),
  };
};
const getStationList = (arr) => {
  return _.flatten(
    arr?.map((x) => {
      return x.children.map((y) => y.value);
    }),
  );
};

export default ({ power = [], onChange = () => {} }) => {
  const [state, setState] = useTRState({
    ...defaultForm(power),
    sequenceOptions: [], // 交易序列
    loadingOptions: false,
    codes: [['market', 'group', 'station']],
  });

  useEffect(() => {
    fetchSeqList();
  }, [state.dates[0], state.dates[1], state.tradeItem.value, JSON.stringify(state.stationList)]);

  const fetchSeqList = async () => {
    // 获取交易序列
    setState({ loadingOptions: true });
    if (state.stationList.length < 1) return;
    const _params = {
      startDate: state.dates[0].format('YYYY-MM-DD'),
      endDate: state.dates[1].format('YYYY-MM-DD'),
      tradeType: state.tradeItem.tradeType,
      stationList: state.stationList,
      marketId: state.market.marketId,
    };
    const res = await querySequence(_params);
    const sequenceOptions = res?.data || [];
    const sequenceIdList = sequenceOptions.map((x) => x.tradeSequenceId);
    state.sequenceOptions = sequenceOptions;
    state.sequenceIdList = sequenceIdList;
    setState({
      sequenceIdList,
      sequenceOptions,
      loadingOptions: false,
    });
    !state.searched && _onFinish();
  };

  const _onFinish = () => {
    // 查询
    setState({ searched: true });
    const { dates, sequenceIdList, stationList, market, groupIds } = state;
    const { operators, tradeType } = state.tradeItem;
    const _params = {
      sequenceId: sequenceIdList,
      stationIds: stationList,
      operators,
      tradeType,
      marketId: market.value,
      provinceId: market.provinceId,
      startDate: dates[0].format('YYYY-MM-DD'),
      endDate: dates[1].format('YYYY-MM-DD'),
      groupIds,
    };
    onChange?.(_params, state.tradeItem); // 通知父级
  };

  const _onReset = () => {
    // 重置
    setState({
      ...defaultForm(power),
      codes: [...state.codes],
      searched: false,
    });
  };

  const changeMaket = (marketId, opt) => {
    setState({
      market: opt,
      stations: opt.children,
      groupIds: opt.children.map((i) => i.value),
      stationList: getStationList(opt.children),
    });
    // 如果是宁夏则默认滚动撮合
    if (opt.provinceId === '64') {
      setState({
        tradeItem: tradeOptions().find((i) => i.value === '滚动'),
      });
    }
  };

  return (
    <Space size={16} wrap>
      <TjSelect
        value={state.market.value}
        options={power}
        onChange={changeMaket}
        showSearch
        filterOption={(input, option) => {
          return (option?.label).toLowerCase().includes(input.toLowerCase());
        }}
      />
      <TjStation
        style={{ width: 160 }}
        value={state.stationList}
        options={state.stations}
        onChange={(stationList) => setState({ stationList })}
      />
      <DatePicker.RangePicker
        style={{ width: 256 }}
        value={state.dates}
        separator="-"
        format={'YYYYMMDD'}
        allowClear={false}
        onChange={(dates) => setState({ dates })}
      />
      <TjSegmented
        value={state.tradeItem.value}
        options={tradeOptions()}
        onChange={(v, tradeItem) => {
          if (state.market.provinceId === '64') {
            return;
          }
          setState({ tradeItem });
        }}
      />
      <TjSelect
        style={{ width: 400 }}
        value={state.sequenceIdList}
        options={state.sequenceOptions}
        onChange={(sequenceIdList) => setState({ sequenceIdList })}
        mode="multiple"
        label="交易序列"
        fieldNames={{ label: 'tradeSequenceName', value: 'tradeSequenceId' }}
        disabled={state.loadingOptions}
      />
      <Space size={16}>
        <Button
          disabled={!state.sequenceOptions.length}
          style={{ width: 98, height: 32 }}
          type="primary"
          onClick={_onFinish}
        >
          查询
        </Button>
        <Button
          disabled={!state.sequenceOptions.length}
          style={{ width: 98, height: 32 }}
          ghost
          onClick={_onReset}
        >
          重置
        </Button>
      </Space>
    </Space>
  );
};
